import React, { Component } from 'react'
import './index.css'
import { Input ,Button,Space,Alert} from 'antd'
import { UserOutlined, LockOutlined } from '@ant-design/icons';

import axios from 'axios'

export default class Login extends Component {

    state ={
        user:'',
        pwd:'',
        warning:false,
        message:''
    }

    // 点击登录
    submitData = async () =>{

        const {user,pwd} = this.state;

        if( user === '') return this.setWarning('用户名不能为空');
        if( pwd  === '') return this.setWarning('密码不能为空');

        let data = await axios.post('/user/login',{user,pwd});

        const {msg,code} = data.data;

        this.setWarning(msg);
        
        if(code === 1){
            localStorage.user = user;
            this.props.history.push('/home')
        }    
    }

    // 控制warning出现
    setWarning = message =>this.setState({message,warning:true})  
    
    render() {
        const {user,pwd,warning,message} = this.state
        return (
            <div className="login">
                <div className="login_div">
                    <Space direction="vertical">

                        <Input prefix={<UserOutlined className="site-form-item-icon" />}  placeholder="请输入用户名" value={user} onChange={ev=>this.setState({user:ev.target.value})}/>
                        <Input.Password prefix={<LockOutlined className="site-form-item-icon" />} placeholder="请输入密码"  value={pwd} onChange={ev=>this.setState({pwd:ev.target.value})}/>
                        <Button type="primary" block onClick={()=>this.submitData()}>登录</Button>
                        {
                            warning?<Alert message={message} type="warning" showIcon closable afterClose={ ()=>this.setState({warning:false})}/>:null
                        }
                    </Space>
                </div>
               
                
            </div>
        )
    }
}

